package net.assassin8.bautista.stalker;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.TextView;

public class Stalker extends Application {

	private static final String TAG = "StalkerApp";
	public static final String PATH = "/sdcard/data/net.assassin8.bautista.stalker/";
	
	private TextView stalkerTextView;
	
	private Context currentContext;

	public void alert(Context ctx, String text) {
		AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
		alertDialog.setMessage(text);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				return;
			}

		});
		alertDialog.show();
	}

	public void downloadMall(Context ctx, long mallId, String mallName,
			String address, String floorNumber2, String description2) {
		StalkerProvider sp = new StalkerProvider(ctx);
		sp.open();
		sp.deletePreviousMall(mallId);
		sp.insertMall(mallId, mallName, address, description2, floorNumber2);

		try {
			Log.i(TAG, "Trying to get floor plans from database");
			URL url = new URL(
					"http://webstalk.bautista.me/stalker/get_floor_plans_xml/"
							+ mallId);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(url.openStream()));
			doc.getDocumentElement().normalize();

			NodeList nodeList = doc.getElementsByTagName("mall");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Log.i(TAG, "Found floor plan");
				// Make buttons first

				Node node = nodeList.item(i);

				Element fstElmnt = (Element) node;

				NodeList idList = fstElmnt.getElementsByTagName("id");
				Element idElement = (Element) idList.item(0);
				idList = idElement.getChildNodes();
				long id = Long
						.parseLong(((Node) idList.item(0)).getNodeValue());

				Log.i(TAG, "Found floor plan id: " + id);

				NodeList floorNumberList = fstElmnt
						.getElementsByTagName("floor_number");
				Element floorNumberElement = (Element) floorNumberList.item(0);
				floorNumberList = floorNumberElement.getChildNodes();
				String floorNumber = ((Node) floorNumberList.item(0))
						.getNodeValue();

				Log.i(TAG, "Found floor number: " + floorNumber);

				NodeList widthList = fstElmnt.getElementsByTagName("width");
				Element widthElement = (Element) widthList.item(0);
				widthList = widthElement.getChildNodes();
				String width = ((Node) widthList.item(0)).getNodeValue();

				Log.i(TAG, "Found width: " + width);

				NodeList heightList = fstElmnt.getElementsByTagName("height");
				Element heightElement = (Element) heightList.item(0);
				heightList = heightElement.getChildNodes();
				String height = ((Node) heightList.item(0)).getNodeValue();

				Log.i(TAG, "Found height: " + height);

				NodeList descriptionList = fstElmnt
						.getElementsByTagName("description");
				Element descriptionElement = (Element) descriptionList.item(0);
				descriptionList = descriptionElement.getChildNodes();
				String description = "";
				try {
					description = ((Node) descriptionList.item(0))
							.getNodeValue();
				} catch (Exception e) {

				}

				Log.i(TAG, "Found description: " + description);

				NodeList imageList = fstElmnt
						.getElementsByTagName("image_filename");
				Element imageElement = (Element) imageList.item(0);
				imageList = imageElement.getChildNodes();
				final String imageFilename = ((Node) imageList.item(0))
						.getNodeValue();

				Log.i(TAG, "Found image filename: " + imageFilename);

				NodeList imageThumbList = fstElmnt
						.getElementsByTagName("image_thumbnail");
				Element imageThumbElement = (Element) imageThumbList.item(0);
				imageThumbList = imageThumbElement.getChildNodes();
				final String imageThumbnail = ((Node) imageThumbList.item(0))
						.getNodeValue();

				Log.i(TAG, "Found image thumbnail: " + imageThumbnail);

				// Download the images
				Log.i(TAG, "Trying to download images");
				ImageManager imageManager = new ImageManager();
				imageManager.downloadFromUrl(
						"http://webstalk.bautista.me/uploads/floor_plans/"
								+ imageFilename, imageFilename);
				imageManager.downloadFromUrl(
						"http://webstalk.bautista.me/uploads/floor_plans/"
								+ imageThumbnail, imageThumbnail);

				NodeList pxmList = fstElmnt
						.getElementsByTagName("pixels_per_meter");
				Element pxmElement = (Element) pxmList.item(0);
				pxmList = pxmElement.getChildNodes();
				String pxm = "0";
				try {
					pxm = ((Node) pxmList.item(0))
							.getNodeValue();
				} catch (Exception e) {

				}

				// Store the entry into the db

				sp.deletePreviousFloorPlans(id);
				sp.insertFloorPlan(id, mallId, floorNumber, width, height,
						description, imageFilename, imageThumbnail,pxm);

				// Start getting the shops
				getShops(ctx, id, sp);
			}
		} catch (Exception e) {
			Log.e("Stalker", "Failed to download floor plans because " + e);
			alert(ctx, "Failed to download floor plans because " + e);
		}
		sp.close();
	}

	private void getShops(Context ctx, long floorPlanId, StalkerProvider sp) {
		try {
			Log.i(TAG, "Trying to insert shops");
			URL url = new URL(
					"http://webstalk.bautista.me/stalker/get_shops_xml/"
							+ floorPlanId);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(url.openStream()));
			doc.getDocumentElement().normalize();

			NodeList nodeList = doc.getElementsByTagName("shops");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Log.i(TAG, "Shop found");
				Node node = nodeList.item(i);

				Element fstElmnt = (Element) node;

				NodeList idList = fstElmnt.getElementsByTagName("id");
				Element idElement = (Element) idList.item(0);
				idList = idElement.getChildNodes();
				final long id = Long.parseLong(((Node) idList.item(0))
						.getNodeValue());

				NodeList nameList = fstElmnt.getElementsByTagName("name");
				Element nameElement = (Element) nameList.item(0);
				nameList = nameElement.getChildNodes();
				final String name = ((Node) nameList.item(0)).getNodeValue();

				NodeList shopCategoryList = fstElmnt
						.getElementsByTagName("shop_category_id");
				Element shopCategoryElement = (Element) shopCategoryList
						.item(0);
				shopCategoryList = shopCategoryElement.getChildNodes();
				final String shopCategoryId = ((Node) shopCategoryList.item(0))
						.getNodeValue();

				NodeList startXList = fstElmnt.getElementsByTagName("start_x");
				Element startXElement = (Element) startXList.item(0);
				startXList = startXElement.getChildNodes();
				final String startX = ((Node) startXList.item(0))
						.getNodeValue();

				NodeList startYList = fstElmnt.getElementsByTagName("start_y");
				Element startYElement = (Element) startYList.item(0);
				startYList = startYElement.getChildNodes();
				final String startY = ((Node) startYList.item(0))
						.getNodeValue();

				NodeList endXList = fstElmnt.getElementsByTagName("end_x");
				Element endXElement = (Element) endXList.item(0);
				endXList = endXElement.getChildNodes();
				final String endX = ((Node) endXList.item(0)).getNodeValue();

				NodeList endYList = fstElmnt.getElementsByTagName("end_y");
				Element endYElement = (Element) endYList.item(0);
				endYList = endYElement.getChildNodes();
				final String endY = ((Node) endYList.item(0)).getNodeValue();

				// Store the entry into the db
				sp.insertShop(id, floorPlanId, name, shopCategoryId, startX,
						startY, endX, endY);
			}
		} catch (Exception e) {
			Log.e("Stalker", "Failed to download shops because: "+e);
			//alert(ctx, "Failed to download shop nodes");
		}
	}

	/*
	 * private void getPathNodes(Context ctx, long floorPlanId, StalkerProvider
	 * sp) { try { Log.i(TAG, "Trying to get path nodes"); URL url = new
	 * URL("http://stalk.bautista.me/xml/get_path_nodes/" + floorPlanId);
	 * DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	 * DocumentBuilder db = dbf.newDocumentBuilder(); Document doc =
	 * db.parse(new InputSource(url.openStream()));
	 * doc.getDocumentElement().normalize();
	 * 
	 * NodeList nodeList = doc.getElementsByTagName("path_nodes");
	 * 
	 * for (int i = 0; i < nodeList.getLength(); i++) { Log.i(TAG,
	 * "Path node found"); Node node = nodeList.item(i);
	 * 
	 * Element fstElmnt = (Element) node;
	 * 
	 * NodeList idList = fstElmnt.getElementsByTagName("id"); Element idElement
	 * = (Element) idList.item(0); idList = idElement.getChildNodes(); final
	 * long id = Long.parseLong(((Node) idList.item(0)) .getNodeValue());
	 * 
	 * NodeList xList = fstElmnt.getElementsByTagName("x"); Element xElement =
	 * (Element) xList.item(0); xList = xElement.getChildNodes(); final String x
	 * = ((Node) xList.item(0)).getNodeValue();
	 * 
	 * NodeList yList = fstElmnt.getElementsByTagName("y"); Element yElement =
	 * (Element) yList.item(0); yList = yElement.getChildNodes(); final String y
	 * = ((Node) yList.item(0)).getNodeValue();
	 * 
	 * // Store the entry into the db sp.insertPathNode(id, floorPlanId, x, y);
	 * } } catch (Exception e) { Log.e("Stalker",
	 * "Failed to download path nodes"); alert(ctx,
	 * "Failed to download path nodes"); }
	 * 
	 * }
	 */

	public void downloadShopCategories(Context ctx) {
		StalkerProvider sp = new StalkerProvider(ctx);
		sp.open();
		sp.deletePreviousShopCategories();
		try {
			Log.i(TAG, "Trying to grab shop categories");
			URL url = new URL(
					"http://webstalk.bautista.me/stalker/get_shop_categories_xml/");
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(url.openStream()));
			doc.getDocumentElement().normalize();

			NodeList nodeList = doc.getElementsByTagName("shop_categories");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Log.i(TAG, "Shop categories found");
				Node node = nodeList.item(i);

				Element fstElmnt = (Element) node;

				NodeList idList = fstElmnt.getElementsByTagName("id");
				Element idElement = (Element) idList.item(0);
				idList = idElement.getChildNodes();
				final long id = Long.parseLong(((Node) idList.item(0))
						.getNodeValue());

				NodeList nameList = fstElmnt.getElementsByTagName("name");
				Element nameElement = (Element) nameList.item(0);
				nameList = nameElement.getChildNodes();
				final String name = ((Node) nameList.item(0)).getNodeValue();

				NodeList descriptionList = fstElmnt
						.getElementsByTagName("description");
				Element descriptionElement = (Element) descriptionList.item(0);
				descriptionList = descriptionElement.getChildNodes();
				String description = "";
				try {
					description = ((Node) descriptionList.item(0))
							.getNodeValue();
				} catch (Exception e) {

				}

				// Store the entry into the db
				sp.insertShopCategory(id, name, description);
			}
		} catch (Exception e) {
			Log.e("Stalker", "Failed to download shop categories because " + e);
			alert(ctx, "Failed to download shop categories because " + e);
		}

		sp.close();

	}

	public void setStalkerTextView(TextView stalkerTextView) {
		this.stalkerTextView = stalkerTextView;
	}

	public TextView getStalkerTextView() {
		return stalkerTextView;
	}

	public void setCurrentContext(Context currentContext) {
		this.currentContext = currentContext;
	}

	public Context getCurrentContext() {
		return currentContext;
	}

	public void setTextStalkerTextView(String string) {
		stalkerTextView.setText(string);
	}

}
